//
//  YOGonline.m
//  YOGProj
//
//  Created by liyun on 14-6-26.
//  Copyright (c) 2014年 liyun. All rights reserved.
//

#import "HCYOGDynamic.h"
#import "HCMacroDefinition.h"
#import "HCSendHttpOperation.h"
#import "YOGonlineDetailInfo.h"
#import "HCDownImageOperation.h"
#import "HCEGORefreshTableHeaderView.h"

static  int length = 80;

@interface HCYOGDynamic ()<UITableViewDataSource,UITableViewDelegate,newProtocol,HCEGORefreshTableHeaderDelegate>
{
    
    int listCount;
    IBOutlet UIScrollView *menuScr;
    IBOutlet UITableView *newsListTable;
    UIImageView *selectImageView;
    NSOperationQueue *m_operationQuene;
    NSMutableArray *newsListArr;
    BOOL                       product_reloading;
    HCEGORefreshTableHeaderView  *refreshHeaderView;
    NSString *cachesDir;
    int type;
    BOOL add;
    UISwipeGestureRecognizer   *recognizerRight;
    UISwipeGestureRecognizer   *recognizerLeft;
}

@property(nonatomic, strong) NSArray *menuItemArr;

@end

@implementation HCYOGDynamic

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        [HCSendHttpOperation shareSendHttpRequest].newsDelegate = self;
    }
    return self;
}

- (void)navigationShowLeft
{
    NSLog(@"左边栏");
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = NSLocalizedString(@"HC青奥动态", @"");
    
//    UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
//    button.frame=CGRectMake(0, 0, 30, 30);
//    [button setBackgroundImage:[UIImage imageWithContentsOfFile:[BUNDLE pathForResource:@"HCmain_menu" ofType:@"png"]] forState:UIControlStateNormal];
//    [button addTarget:self action:@selector(navigationShowLeft) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *barItemleft=[[UIBarButtonItem alloc]initWithCustomView:button];
//    self.navigationItem.leftBarButtonItem=barItemleft;
    
    int height                  = (MODEL?568:480)-64;
    newsListTable                = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, height)
                                                               style:UITableViewStylePlain];
    newsListTable.delegate       = self;
    newsListTable.dataSource     = self;
    newsListTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view                  addSubview:newsListTable];
    
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    cachesDir = [paths objectAtIndex:0];
    
    m_operationQuene = [[NSOperationQueue alloc] init];
    [m_operationQuene setMaxConcurrentOperationCount:10];
    
    type = 1;
    
    [[HCSendHttpOperation shareSendHttpRequest] getNews:1
                                                 pageNo:1
                                               pageSize:10];
    [HCSendHttpOperation shareSendHttpRequest].newsDelegate = self;
}

- (void)passNew:(NSDictionary *)paramDic
{
    NSArray *buttonArr = [[NSArray alloc] initWithArray:menuScr.subviews];
    for(UIButton *button in buttonArr)
    {
        if(button.tag >0)
        {
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            if(type == button.tag)
                [button setTitleColor:BACK_IMAGE_COLOR forState:UIControlStateNormal];
        }
    }
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    selectImageView.frame = CGRectMake(5+length*(type-1), 45, length-10, 4);
    if(selectImageView.frame.origin.x >240)
    {
        menuScr.contentOffset = CGPointMake(240, 0);
    }
    else if(selectImageView.frame.origin.x<0)
    {
        menuScr.contentOffset = CGPointMake(80, 0);
    }
    else
    {
        menuScr.contentOffset = CGPointMake(0, 0);
    }
    [UIView commitAnimations];
    
    
    if(!newsListArr)
        newsListArr = [[NSMutableArray alloc] init];
    
    if(!add)
        [newsListArr removeAllObjects];
    
    listCount = [[[[paramDic objectForKey:@"retData"] objectForKey:@"page"] objectForKey:@"count"] intValue];
    
    [newsListArr addObjectsFromArray:[[paramDic objectForKey:@"retData"] objectForKey:@"news"]];
    
    
    [newsListTable reloadData];
    [self pullRefresh];
    if(!add)
        [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0];
}

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 180;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return newsListArr.count +1;
}

- (NSString *)curpString:(NSString *)str
{
    NSRange range1=[str rangeOfString:@"/" options:NSBackwardsSearch];
    if(range1.location <100)
    {
        str = [str substringFromIndex:range1.location+1];
    }
    return  str;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
    }
    
    NSArray *subArr = [[NSArray alloc] initWithArray:cell.contentView.subviews];
    for (UIView *view in subArr)
    {
        [view removeFromSuperview];
    }
    
    if(newsListArr.count > indexPath.row)
    {
        UIImageView *image  = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 160)];
        image.image = [UIImage imageWithContentsOfFile:[BUNDLE pathForResource:@"HCdefaultImage" ofType:@"png"]];
        [cell.contentView addSubview:image];
        
        if([[newsListArr[0] objectForKey:@"pictures"] count] != 0)
        {
            NSString *urlStr = [[newsListArr[indexPath.row] objectForKey:@"pictures"][0] objectForKey:@"url"];
            
            NSString *imageName = [NSString stringWithFormat:@"%@",[self curpString:urlStr]];
            NSString *imageDocu = [cachesDir stringByAppendingPathComponent:imageName];
            
            if([[NSFileManager defaultManager] fileExistsAtPath:imageDocu])
            {
                image.image = [UIImage imageWithContentsOfFile:imageDocu];
            }
            else
            {
                if(urlStr.length >= 20)
                {
                    HCDownImageOperation *diOperation=[[HCDownImageOperation alloc]
                                                     initWithUrl:urlStr
                                                     imageView:image
                                                     imageId:imageName
                                                     isRect:YES];
                    [m_operationQuene addOperation:diOperation];
                }
            }
            
            UIImageView *backImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 130, 320, 30)];
            backImg.backgroundColor = [UIColor blackColor];
            backImg.alpha= 0.7;
            [image addSubview:backImg];
            
            UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(5, 130, 310, 30)];
            title.text = [newsListArr[indexPath.row] objectForKey:@"title"];
            title.textColor = [UIColor whiteColor];
            title.font = HEIGHT_FONT(14.0f);
            title.backgroundColor = [UIColor clearColor];
            [cell.contentView addSubview:title];
        }
    }
    else
    {
        int height;
        height = type==1?160:80;
        
        if(newsListArr.count == 0)
            height = 160;
        
        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, height)];
        title.text = (newsListArr.count!=listCount)?NSLocalizedString(@"HC点击加载更多", @""):NSLocalizedString(@"HC已全部加载", @"");
        title.textAlignment = NSTextAlignmentCenter;
        title.font = HEIGHT_FONT(14.0f);
        title.backgroundColor = [UIColor whiteColor];
        title.textColor = (newsListArr.count!=listCount)?[UIColor blackColor]:[UIColor lightGrayColor];
        [cell.contentView addSubview:title];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row < newsListArr.count)
    {
        YOGonlineDetailInfo *instance = [[YOGonlineDetailInfo alloc] init];
        instance.detailInfoDic = newsListArr[indexPath.row];
        [self.navigationController pushViewController:instance animated:YES];
    }
    else
    {
        if(newsListArr.count != listCount)
        {
            int page;// = newsListArr.count/10+1;
            
            if(newsListArr.count >= 1)
            {
                page = (newsListArr.count-1)/10+2;
            }
            else
                page = 1;
            
            add = true;
            
            [[HCSendHttpOperation shareSendHttpRequest] getNews:type
                                                       pageNo:page
                                                     pageSize:10];
            [HCSendHttpOperation shareSendHttpRequest].newsDelegate = self;
        }
    }
}

#pragma mark 重新加载下拉框
- (void)pullRefresh
{
    if(refreshHeaderView)
        [refreshHeaderView removeFromSuperview];
    refreshHeaderView = [[HCEGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0, -80, 320, 80)];
    refreshHeaderView.delegate = self;
    [newsListTable addSubview:refreshHeaderView];
    [refreshHeaderView refreshLastUpdatedDate];
}

#pragma mark EGORefreshTableHeaderDelegate(上下下拉操作)
- (void)reloadTableViewDataSource
{
	product_reloading = YES;
	NSLog(@"开始获取更多数据...");
	//打开线程，加载更多数据
    add = false;
    
    [[HCSendHttpOperation shareSendHttpRequest] getNews:type
                                               pageNo:1
                                             pageSize:10];
    [HCSendHttpOperation shareSendHttpRequest].newsDelegate = self;
}

- (void)doneLoadingTableViewData
{
    NSLog(@"加载更多结束");
	product_reloading = NO;
    [refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:newsListTable];
}

#pragma mark UIScrollViewDelegate(上拉下拉判断)
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [refreshHeaderView egoRefreshScrollViewDidScroll:newsListTable];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [refreshHeaderView egoRefreshScrollViewDidEndDragging:newsListTable];
}


#pragma mark EGORefreshTableHeaderDelegate Methods
- (void)egoRefreshTableHeaderDidTriggerRefresh:(HCEGORefreshTableHeaderView*)view
{
	[self reloadTableViewDataSource];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(HCEGORefreshTableHeaderView*)view
{
	return product_reloading;
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(HCEGORefreshTableHeaderView*)view
{
	return [NSDate date];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
